from flask import Blueprint, request, session
from utils import db, response

us = Blueprint('users', __name__)

@us.route('/api/users', methods=['POST'])
def get_users():
    '''用户登录'''
    acount = request.json.get("acount")
    password = request.json.get("password")
    # role = request.json.get("role")
    
    result = db.fetch_one("select * from `user_list` where acount=%s and password=%s", [acount, password])
    print(result)
    
    if result:
        session["user_info"] = {"id":result['id'],"acount":result['acount'],"role":result['role']}
        return response.res_200(message="登录成功", data=result)
    
    else:
        return response.res_200(code=201, message="账号或密码错误")
    
@us.route('/api/role', methods=['GET'])
def get_role():
    '''获取用户角色'''
    session_info = session.get("user_info")
    if not session_info:
        return response.res_200(code=201, message="请先登录")
    
    role = session_info.get("role")
    if role == 1:
        sql = "select * from `user_list` left join `writer` on user_list.id=writer.user_id where user_list.role=%s"
        params = [session_info["id"]]
        result = db.fetch_all(sql, params)
        
        return response.res_200(message=f"已获取用户角色{role}", data=result)
    
    else:
        sql = "select * from `user_list` left join  `writer` on user_list.id=writer.user_id"
        params = []
        result = db.fetch_all(sql, params)
        
        return response.res_200(message=f"已获取用户角色{role}", data=result)
    

    